package com.commerceerp.system.pay;

import com.commerceerp.system.service.ImageService;
import io.swagger.annotations.Api;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.InputStream;
import java.util.Map;

/**
 * Created by Administrator on 2018/8/23 0023.
 */
@Slf4j
@Api(description = "支付回调接口", value = "支付回调接口")
@Controller
@RequestMapping("pay")
public class PayController {

    @Autowired
    private ImageService imageService;

    //微信支付成功回调地址
    @RequestMapping(value = "/weixinpay/callback", method = RequestMethod.POST)
    public String callBack(HttpServletRequest request, HttpServletResponse response) throws Exception {

        try {
            InputStream is = request.getInputStream();
            String xml = CommonUtil.inputStream2String(is, "UTF-8");
            log.info(xml);
            Map<String, String> map = CommonUtil.parseXml(xml);
            log.info(map.toString());
            if ("SUCCESS".equalsIgnoreCase(map.get("result_code")
                    .toString())) {
                // 对数据库的操作
                String outTradeNo =  map.get("out_trade_no");
                imageService.rechargeBack(outTradeNo);
                return PayCommonUtil.setXML("SUCCESS", "OK");
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
        return null;
    }

    @RequestMapping(value = "/alipay/callback")
    public String aliPaycallBack(HttpServletRequest request, HttpServletResponse response) throws Exception {
        String orderId = request.getParameter("out_trade_no");
        String totalAmount = request.getParameter("total_amount");
        String tradeStatus = request.getParameter("trade_status");
        log.info("交易状态:" + tradeStatus);
        log.info("订单号:" + orderId + ",订单金额:" + totalAmount);
        log.info("支付宝异步回调通知:" + AliPayCode.toMap(request).toString());
        if (tradeStatus.equals("TRADE_SUCCESS")) {
            System.out.println("订单支付成功！");
            imageService.rechargeBack(orderId);
            return "success";
        }
        log.info("系统订单业务处理完成");
        //ResponseWriteUtil.writeHTML("success");// 告诉支付宝我已处理，不需要重复发异步通知
        log.info("支付宝异步回调通知成功结束");
        return "false";
    }
}
